<?php
declare (strict_types=1);

namespace app\api\version\v1;
;
use app\common\controller\Api;
use app\common\util\AlipayAppUtil;
use app\common\util\WeChatAppUtil;
use Exception;
use think\App;
use think\facade\Db;
use think\facade\Log;

/**
 * | Notes：支付管理
 * +----------------------------------------------------------------------
 * | PHP Version 7.2+
 * +----------------------------------------------------------------------
 * | Copyright (c) 2011-2020 https://www.xxq.com.cn, All rights reserved.
 * +----------------------------------------------------------------------
 * | Author: 和好 <389123492@qq.com>
 * +----------------------------------------------------------------------
 * | Date: 2021/2/27 17:15
 * +----------------------------------------------------------------------
 */
class Payment extends Api
{
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
    }


    public function weChatAppNotify()
    {
        $xml = file_get_contents("php://input");

        $weChatAppUtil = new WeChatAppUtil;
        //xml数据转数组
        $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        Log::record('微信支付回调：' . json_encode($data));
        //保存微信服务器返回的签名sign
        $data_sign = $data['sign'];
        //sign不参与签名算法
        unset($data['sign']);
        $sign = $weChatAppUtil->createSign($data);
        Log::record('微信支付回调：' . $sign);

        //判断签名是否正确,判断支付状态
        if (($sign === $data_sign) && ($data['return_code'] == 'SUCCESS') && ($data['result_code'] == 'SUCCESS')) {
            Log::record('微信支付回调：验证成功');
            $results = $data;
            //获取服务器返回的数据
            $order_sn = $data['out_trade_no'];    //订单号
//            $order_id = $data['attach'];        //附加参数,选择传递订单ID
            $openid = $data['openid'];            //付款人openID
            $total_fee = $data['total_fee'];    //付款金额

            Log::record('微信支付回调：订单号'.$order_sn);
            //更新状态
            echo OrderService::OrderNotify($order_sn);
        } else {
            $results = false;
        }

        //返回状态给微信服务器
        if ($results) {
            $str = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        } else {
            $str = '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
        }
        echo $str;die;
    }
}